const express = require('express');
const router = express.Router();
const Destination = require('../models/Destination');
const Attraction = require('../models/Attraction');
const { auth } = require('../middleware/auth');
const { logger } = require('../utils/logger');

// 获取所有目的地列表 (支持分页、搜索、筛选)
router.get('/', async (req, res) => {
  const requestId = req.requestId;
  
  try {
    logger.info(`开始获取目的地列表`, { requestId });

    const {
      page = 1,
      limit = 10,
      search,
      category,
      sortBy = 'popularLevel',
      sortOrder = 'desc',
      minRating,
      maxPrice,
      country
    } = req.query;

    // 构建查询条件
    const query = { status: 'active' };

    // 搜索条件
    if (search) {
      query.$text = { $search: search };
    }

    // 分类筛选
    if (category && category !== 'all') {
      query.category = category;
    }

    // 国家筛选
    if (country) {
      query.country = country;
    }

    // 评分筛选
    if (minRating) {
      query.rating = { $gte: parseFloat(minRating) };
    }

    // 价格筛选
    if (maxPrice) {
      query['priceRange.max'] = { $lte: parseFloat(maxPrice) };
    }

    // 排序选项
    const sortOptions = {};
    switch (sortBy) {
      case 'rating':
        sortOptions.rating = sortOrder === 'desc' ? -1 : 1;
        break;
      case 'name':
        sortOptions.name = sortOrder === 'desc' ? -1 : 1;
        break;
      case 'price':
        sortOptions['priceRange.min'] = sortOrder === 'desc' ? -1 : 1;
        break;
      case 'popular':
        sortOptions.popularLevel = -1;
        sortOptions.reviewCount = -1;
        break;
      default:
        sortOptions.popularLevel = -1;
    }

    // 分页计算
    const skip = (parseInt(page) - 1) * parseInt(limit);

    // 执行查询
    const [destinations, total] = await Promise.all([
      Destination.find(query)
        .sort(sortOptions)
        .skip(skip)
        .limit(parseInt(limit))
        .select('-__v')
        .lean(),
      Destination.countDocuments(query)
    ]);

    // 计算分页信息
    const totalPages = Math.ceil(total / parseInt(limit));

    logger.info(`目的地列表获取成功`, {
      requestId,
      count: destinations.length,
      total,
      page: parseInt(page),
      totalPages
    });

    res.json({
      success: true,
      data: {
        destinations,
        pagination: {
          currentPage: parseInt(page),
          totalPages,
          totalCount: total,
          pageSize: parseInt(limit),
          hasNext: parseInt(page) < totalPages,
          hasPrev: parseInt(page) > 1
        }
      }
    });

  } catch (error) {
    logger.error(`获取目的地列表失败`, { requestId, error: error.message });
    res.status(500).json({
      success: false,
      message: '获取目的地列表失败',
      error: error.message
    });
  }
});

// 获取目的地详情
router.get('/:id', async (req, res) => {
  const requestId = req.requestId;
  
  try {
    const { id } = req.params;
    const { includeAttractions = true, includeHotels = true, includeNearby = true } = req.query;

    logger.info(`开始获取目的地详情`, { requestId, destinationId: id });

    // 获取目的地基本信息
    let destination = await Destination.findById(id)
      .select('-__v')
      .lean();

    if (!destination) {
      return res.status(404).json({
        success: false,
        message: '目的地不存在'
      });
    }

    // 并行获取关联数据
    const promises = [];

    // 获取关联景点
    if (includeAttractions === 'true' && destination.attractions?.length > 0) {
      promises.push(
        Attraction.find({ 
          _id: { $in: destination.attractions },
          status: 'active'
        })
        .select('name nameEn description image rating reviewCount priceRange coordinates')
        .lean()
        .then(attractions => ({ attractions }))
      );
    } else {
      promises.push(Promise.resolve({ attractions: [] }));
    }

    // 获取关联酒店 (暂时使用模拟数据)
    if (includeHotels === 'true') {
      promises.push(Promise.resolve({ hotels: [] }));
    } else {
      promises.push(Promise.resolve({ hotels: [] }));
    }

    // 获取附近目的地
    if (includeNearby === 'true' && destination.coordinates) {
      promises.push(
        Destination.find({
          _id: { $ne: destination._id },
          coordinates: {
            $near: {
              $geometry: {
                type: 'Point',
                coordinates: [destination.coordinates.lng, destination.coordinates.lat]
              },
              $maxDistance: 100000 // 100公里
            }
          },
          status: 'active'
        })
        .limit(5)
        .select('name nameEn image rating coordinates')
        .lean()
        .then(nearby => ({ nearbyDestinations: nearby }))
      );
    } else {
      promises.push(Promise.resolve({ nearbyDestinations: [] }));
    }

    // 等待所有查询完成
    const [attractionsResult, hotelsResult, nearbyResult] = await Promise.all(promises);

    // 组装完整数据
    const result = {
      ...destination,
      ...attractionsResult,
      ...hotelsResult,
      ...nearbyResult
    };

    logger.info(`目的地详情获取成功`, {
      requestId,
      destinationId: id,
      attractionsCount: result.attractions?.length || 0,
      hotelsCount: result.hotels?.length || 0,
      nearbyCount: result.nearbyDestinations?.length || 0
    });

    res.json({
      success: true,
      data: result
    });

  } catch (error) {
    logger.error(`获取目的地详情失败`, { requestId, error: error.message });
    res.status(500).json({
      success: false,
      message: '获取目的地详情失败',
      error: error.message
    });
  }
});

// 获取目的地的景点列表
router.get('/:id/attractions', async (req, res) => {
  const requestId = req.requestId;
  
  try {
    const { id } = req.params;
    const { page = 1, limit = 10 } = req.query;

    logger.info(`开始获取目的地景点列表`, { requestId, destinationId: id });

    // 验证目的地是否存在
    const destination = await Destination.findById(id).select('_id name');
    if (!destination) {
      return res.status(404).json({
        success: false,
        message: '目的地不存在'
      });
    }

    // 分页计算
    const skip = (parseInt(page) - 1) * parseInt(limit);

    // 获取景点列表
    const [attractions, total] = await Promise.all([
      Attraction.find({ 
        destination: id,
        status: 'active'
      })
      .sort({ popularLevel: -1, rating: -1 })
      .skip(skip)
      .limit(parseInt(limit))
      .select('-__v')
      .lean(),
      Attraction.countDocuments({ 
        destination: id,
        status: 'active'
      })
    ]);

    const totalPages = Math.ceil(total / parseInt(limit));

    logger.info(`目的地景点列表获取成功`, {
      requestId,
      destinationId: id,
      count: attractions.length,
      total
    });

    res.json({
      success: true,
      data: {
        destination: {
          _id: destination._id,
          name: destination.name
        },
        attractions,
        pagination: {
          currentPage: parseInt(page),
          totalPages,
          totalCount: total,
          pageSize: parseInt(limit)
        }
      }
    });

  } catch (error) {
    logger.error(`获取目的地景点列表失败`, { requestId, error: error.message });
    res.status(500).json({
      success: false,
      message: '获取目的地景点列表失败',
      error: error.message
    });
  }
});

// 搜索附近目的地
router.post('/:id/nearby', async (req, res) => {
  const requestId = req.requestId;
  
  try {
    const { id } = req.params;
    const { maxDistance = 50, limit = 10 } = req.body;

    logger.info(`开始搜索附近目的地`, { requestId, destinationId: id, maxDistance });

    // 获取当前目的地坐标
    const destination = await Destination.findById(id).select('coordinates');
    if (!destination || !destination.coordinates) {
      return res.status(404).json({
        success: false,
        message: '目的地不存在或缺少坐标信息'
      });
    }

    // 搜索附近目的地
    const nearbyDestinations = await Destination.find({
      _id: { $ne: id },
      coordinates: {
        $near: {
          $geometry: {
            type: 'Point',
            coordinates: [destination.coordinates.lng, destination.coordinates.lat]
          },
          $maxDistance: maxDistance * 1000 // 转换为米
        }
      },
      status: 'active'
    })
    .limit(parseInt(limit))
    .select('name nameEn image rating coordinates country')
    .lean();

    logger.info(`附近目的地搜索成功`, {
      requestId,
      destinationId: id,
      count: nearbyDestinations.length
    });

    res.json({
      success: true,
      data: {
        center: destination.coordinates,
        maxDistance,
        destinations: nearbyDestinations
      }
    });

  } catch (error) {
    logger.error(`搜索附近目的地失败`, { requestId, error: error.message });
    res.status(500).json({
      success: false,
      message: '搜索附近目的地失败',
      error: error.message
    });
  }
});

module.exports = router; 